package com.bdzl.ecs.util.electronicUtils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @author DK
 * @date 2019-01-07 18:43
 **/
public class FileBase64Util {
    public static String getFileBase64(MultipartFile file){
        try {
            byte[] buffer  = file.getBytes();
            return new BASE64Encoder().encode(buffer).replaceAll("\n","").replaceAll("\r","");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }


    //base64字符串转化成图片

    /**
     *生成临时文件 记得把临时文件清掉 tmpFile.deleteOnExit();
     * @param imgStr
     * @return
     */
    public static File getImage(String imgStr)
    {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成jpeg图片
            File tmpFile = File.createTempFile("temporary",".jpg");
//            String imgFilePath = "D:\\tupian\\new.jpg";//新生成的图片
            OutputStream out = new FileOutputStream(tmpFile);
            out.write(b);
            out.flush();
            out.close();


            return tmpFile;
        }
        catch (Exception e)
        {
            return null;
        }
    }


    public static String sendGetFile(String url, String filePath) {
        String sResponse="";
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost uploadFile = new HttpPost(url);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            File f = new File(filePath);
            // 把文件加到HTTP的post请求中
            builder.addBinaryBody(
                    "code_file",
                    new FileInputStream(f),
                    ContentType.APPLICATION_OCTET_STREAM,
                    f.getName()
            );
            HttpEntity multipart = builder.build();
            uploadFile.setEntity(multipart);
            CloseableHttpResponse response = httpClient.execute(uploadFile);
            HttpEntity responseEntity = response.getEntity();
            sResponse  = EntityUtils.toString(responseEntity, "UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        return sResponse;
    }

}
